﻿using System;
using System.IO;
using Newtonsoft.Json;
using TrafficCountingTool.Models;

namespace TrafficCountingTool.Core
{
    public static class ProjectFileHelper
    {
        public static void Save(string path, ProjectFile storageFile)
        {
            if (!File.Exists(path))
            {
                storageFile.CreateTime = DateTime.Now;
            }

            storageFile.LastModifyTime = DateTime.Now;

            var json = JsonConvert.SerializeObject(storageFile);

            using (StreamWriter writer = new StreamWriter(path, false))
            {
                writer.Write(json);
            }
        }

        public static ProjectFile Load(string path)
        {
            if (!File.Exists(path))
            {
                throw new IOException("文件不存在" + path);
            }

            string json;
            using (StreamReader reader = new StreamReader(path))
            {
                json = reader.ReadToEnd();
            }

            // try
            try
            {
                return JsonConvert.DeserializeObject<ProjectFile>(json);
            }
            catch
            {
                return null;
            }
        }
    }
}